package com.duke.finca.web;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.duke.finca.domain.Entradas;
import com.duke.finca.service.EntradasService;
import com.duke.finca.util.ConstantWebApp;

@Controller("consultaEntradaActionBean")
@Scope(value = "session")
public class ConsultaEntradaActionBean extends GenericReportAction{

    Logger log = Logger.getLogger(ConsultaEntradaActionBean.class);

    @Autowired
    private EntradasService entradasService;
    
    private Entradas entradas=new Entradas();
    
    private List<Entradas> listEntrada = new ArrayList<Entradas>();
    
	public Entradas getEntradas() {
		return entradas;
	}

	public void setEntradas(Entradas entradas) {
		this.entradas = entradas;
	}

	public List<Entradas> getListEntrada() {
		return listEntrada;
	}

	public void setListEntrada(List<Entradas> listEntrada) {
		this.listEntrada = listEntrada;
	}

	public void entradas(){
    	System.out.println("listar entradas");
    	listEntrada = entradasService.selectAll();
    	if(listEntrada.isEmpty()){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,"", "No se encontraron elementos!"));
        }
    	
    }
	public void edit(Integer id){
		System.out.println("Id modificar: "+id);
		
		entradas=entradasService.selectByPrimaryKey(id);
		
		
	}
	public void hola(){
		System.out.println("hola!!!");
	}
	public void grabar(Integer id){
		System.out.println("Grabar!!!");
		try {
			if(entradas!=null){
				if(entradas.getId()!=null){// update
					entradasService.updateSelective(entradas);
				}else{// insert
					
				}
				entradas();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	public void agregarEntrada() {
        log.info("Metodo agregarEntrada ejecutado");
        try {
        	entradasService.save(entradas);
        	buscarEntradas();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Informacion", "Se agrego la entrada exitosamente"));
        } catch (Exception e) {
            log.error("Error en agregarEntrada:" + e.getMessage(), e);
        }


    }
//	public void imprimir(String formato){
//		try{
//			FacesContext context=FacesContext.getCurrentInstance();
//			ServletContext servletContext=(ServletContext)context.getExternalContext().
//											getContext();
//			InputStream inputStream=servletContext.getResourceAsStream("reportes/Rpt_Control_Ganados.jasper");
//			//InputStream imgLogoSt = servletContext.getResourceAsStream("img/logo_finca.jpg");			
//			
//			HttpServletResponse response=(HttpServletResponse)context.getExternalContext().
//											getResponse();
//			response.addHeader("Content-Disposition", "attachment; filename=Reporte.pdf");
//			response.setContentType("application/pdf");
//			HashMap<String, Object> paramReport = new HashMap<String, Object>();
//			//paramReport.put("P_IMAGEN_LOGO", imgLogoSt);
//			paramReport.put("sede", entradas.getSede());
//			JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(listEntrada);
//			JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, paramReport, dataSource);
//				
//			JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
//			context.getApplication().getStateManager().saveView(context);
//			context.responseComplete();
//			
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//		
//	}
	public void imprimir(String formato){
		
		try {
			//String rutaImagenLogo = ConstantWebApp.RUTA_IMAGEN_REPORTE;
			String rutaReporte = "/reportes/Rpt_Control_Ganados.jasper";
			
//			InputStream reportConsultaGestorSt = getResourceInputStream(rutaReporte);
//			InputStream imgLogoSt = getResourceInputStream(rutaImagenLogo);
			HashMap<String, Object> paramReport = new HashMap<String, Object>();
			//paramReport.put("P_IMAGEN_LOGO", imgLogoSt);
			//paramReport.put("P_REPORT", reportConsultaGestorSt);
			paramReport.put("sede", entradas.getSede());
			paramReport.put("corralControl", entradas.getCorralControl());			
			this.setTypeExportFile(formato);
			this.setJasperFile(rutaReporte);
			this.setList(listEntrada);
			this.setParameters(paramReport);
			this.setReportName("ListaEntrada_Cede_" + entradas.getSede());
			this.createReport();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//		
	}
	
    
    public void buscarEntradas(){
    	System.out.println("colaboradores: " + entradas.getCodProveedor());
    	
    	listEntrada = entradasService.find(entradas);
    	if(listEntrada.isEmpty()){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,"", "No se encontraron elementos!"));
        }
    	
    }
    
    public void clean() {
        log.debug("Limpiar registro colaborador");
        entradas = new Entradas();
    }

	public EntradasService getEntradasService() {
		return entradasService;
	}

	public void setEntradasService(EntradasService entradasService) {
		this.entradasService = entradasService;
	}   
}
